from django.shortcuts import render,redirect,HttpResponseRedirect
from Post.models import Question, Choice
from django.contrib.auth import logout

# Create your views here.
# 用户发来的请求，将会作为第一个参数传给函数，所以需要用一个变量来接收
def index(request):
    username = request.session.get('name','游客')
    print("name: ",username)
    questions = Question.objects.order_by('-release_time')
    # 通过render函数找到名为 index.html 的模板文件，返回给用户
    return render(request, 'index.html', {'questions':questions,'username':username})

def detail(request, q_id):
    # url上的数字作为参数传给q_id
    # 字典内容将以key=value的形式。传给detail.html，detail.html就会拥有变量
    question = Question.objects.get(id=q_id)
    return render(request, 'detail.html', {'question':question})

def votes(request, q_id):
    c_id = request.POST.get('c_id')
    question = Question.objects.get(id=q_id) # 取出给哪个问题投票
    # 在用于请求的POST对象中取出c_id的值。POST是一个字典，通过get方法取值
    if c_id: # 如果c_id不为空，取出具体的选项，将其票数加1
        choice = question.choice_set.get(id=c_id)
        choice.vote += 1
        choice.save()
    return redirect('/Post/{}/res/'.format(q_id))

def res(request, q_id):
    question = Question.objects.get(id=q_id)
    return render(request, 'result.html', {'question':question})

def login(request):
    return render(request, 'login.html')

def showmain(request):
    username = request.POST.get('username')
    request.session['name'] = username
    return redirect('/Post')

def quit(request):
    logout(request)
    request.session.clear()
    return redirect('/Post')

